// QiangPiaoShenQi.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "QiangPiaoShenQi.h"
#include "B5MCommon/ProcHelper.h"
#include "ConfigFile.h"
#include "B5MCommon/StringHelper.h"
#include "B5MCommon/FileHelper.h"
#include "B5MCommon/Logger.h"

#define MAX_LOADSTRING 100
#define DLL_FILENAME L"\\HuangNiu.dll"
//#define DLL_FILENAME L"\\QiangPiaoShenQi.dll"

// Global Variables:
HINSTANCE hInst;								// current instance
TCHAR szTitle[MAX_LOADSTRING];					// The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];			// the main window class name

typedef int (WINAPI *FnUIMain)(HINSTANCE hInstance, LPTSTR lpstrCmdLine, int nCmdShow);

int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

#ifdef _DEBUG
	wstring strPath = CProcHelper::GetCurrentProcessPath() + DLL_FILENAME;
#else
	ConfigFile cfg;
	string ver = cfg.GetVersion();
	if (ver.empty())
		ver = "default";

	wstring strPath = CProcHelper::GetCurrentProcessPath() + L"\\Application\\" + CStringHelper::UTF82Unicode(ver) + DLL_FILENAME;
#endif
	HMODULE hModMain = LoadLibrary(strPath.c_str());
#ifndef _DEBUG
	if (hModMain == NULL)
	{
		DEBUGW(DBG_ERROR, L"load dll failed first: " << strPath);
		wstring strAppDir = CProcHelper::GetCurrentProcessPath() + L"\\Application";
		vector<wstring> arrSubDirs;
		CFileHelper::FindAllSubDirs(strAppDir, arrSubDirs);
		for (vector<wstring>::iterator it=arrSubDirs.begin(); it!=arrSubDirs.end(); it++)
		{
			strPath = *it + DLL_FILENAME;
			hModMain = LoadLibrary(strPath.c_str());
			if (hModMain != NULL)
				break;
		}
	}
#endif

	if (hModMain == NULL)
	{
		DEBUGW(DBG_ERROR, L"load dll failed finally: " << strPath);
		return 0;
	}

	FnUIMain fnMain = (FnUIMain)GetProcAddress(hModMain, "UIMain");
	if (fnMain == NULL)
	{
		DEBUGA(DBG_ERROR, "load function UIMain failed.");
		return 0;
	}

	return fnMain(hInstance, lpCmdLine, nCmdShow);
}
